
import React, { useState, useEffect, useRef } from 'react';


import '../../../../node_modules/react-grid-layout/css/styles.css'
import '../../../../node_modules/react-resizable/css/styles.css'
import { Row, Col, Card, Tabs, Divider, Image, message, List,Button,Space,Tooltip } from 'antd';
import styles from './index.less';

import ECharts from 'echarts-for-react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import GridLayout from 'react-grid-layout';
const ResponsiveGridLayout = WidthProvider(Responsive);



import { updateDeviceType } from '@/services/devicetype';
import { CloseOutlined } from '@ant-design/icons';  
import { queryDeviceAttrList} from '@/services/deviceattr';

import SelectAttr from './components/selectattr';
import SelectState from './components/selectstate';

import AddTabs from './components/addtabs';
import UpdateTabs from './components/updatetabs';
import AlarmTable from '@/pages/monitoring/deviceAlarm';
import muban1 from '@/assets/muban1.png';
import muban2 from '@/assets/muban2.png';
import muban3 from '@/assets/muban3.png';
import muban4 from '@/assets/muban4.png';
import muban5 from '@/assets/muban5.png';



let modal=[{
  key:0,text:"状态栏",value:{color:'red',filed:'',text:''}
},{
  key:1,text:"内容模块1",img:muban1,value:{picCode:'',unit:'red',filed:'',text:'',abb:''
  ,children:[{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''}]
  ,position:[ {i: 'a', x: 0, y: 0, w: 3, h: 3}]
}
},{
  key:2,text:"内容模块2",img:muban2,value:{picCode:'',unit:'red',text:'',fileds:[{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''}]}
},{
  key:3,text:"内容模块3",img:muban3,value:{picCode:'',unit:'red',filed:'',text:'',abb:'',children:[{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''}]}
},{
  key:4,text:"内容模块4",img:muban4,value:{picCode:'',unit:'red',filed:'',text:'',abb:'',children:[{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''}]}
},{
  key:5,text:"内容模块5",img:muban5,value:{picCode:'',unit:'red',filed:'',text:'',abb:'',children:[{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''},{filed:'',abb:''}]}
},{
  key:66,text:"报警指示"}
,{
  key:77,text:"跳闸指示"
}]

const initialItems = [
  
  {
    label: '报警记录',
    children: 'Content of Tab 3',
    key: '2',
    closable: false,
  },
];

const details: React.FC = (props: any) => {
  // const { device } = props.match;

  var { deviceType } = props.location.state;
  const device={deviceId:80000002,deviceTypeId:1};
  const [selectAttrModalVisible, handleSelectAttrModalVisible] = useState<boolean>(false);
  const [selectStateModalVisible, handleSelectStateModalVisible] = useState<boolean>(false);

  const [attrlist, setAttrlist] = useState<API.SysDeviceAttrItem[]>();
  const [alarmlist] = useState([{'alarmDes':'报警1'},{'alarmDes':'报警2'},{'alarmDes':'报警3'},{'alarmDes':'报警4'},{'alarmDes':'报警5'},{'alarmDes':'报警6'},{'alarmDes':'报警7'},{'alarmDes':'报警8'}]);

  const [formValues, setFormValues] = useState({});
  const [activeKey, setActiveKey] = useState(0);
  const [updateIndex, setUpdateIndex] = useState();
  const [designAttrList, setDesignAttrlist] = useState([]);
  const [designStateList, setDesignStatelist] = useState([]);
  const [attrLayout, setAttrLayout] = useState([])
  const [stateLayout, setStateLayout] = useState([])
  const [items, setItems] = useState(initialItems);
  const [tabModalVisible, handTabModalVisible] = useState<boolean>(false);
  const [updateTabModalVisible, handUpdateTabModalVisible] = useState<boolean>(false);
  const [activeLabel, setActiveLabel] = useState();


  useEffect(() => {
    
    const setSelectData = async () => {
      var attrs = await queryDeviceAttrList({"deviceTypeId":device.deviceTypeId});
      setAttrlist(attrs);
      let template=deviceType.template;
      if(template!=null){
        template=JSON.parse(template);
        setItems(template?.tabitem);
        setAttrLayout(template?.attrLayout||[]);
        setStateLayout(template?.stateLayout||[]);
        setDesignAttrlist(template?.attrList);
        setDesignStatelist(template?.stateList);
      }
    }
    setSelectData();
  }, []);


  const changelayout = async (Layouts) =>  {
    console.log("-------------------------- /")
    console.log(Layouts)
    setAttrLayout(Layouts)
  }

  const changelayout1 = async (Layouts) =>  {
    console.log("1-------------------------- //")
    console.log(Layouts)
    setStateLayout(Layouts)
  }

  const toAddDesign = async (item) =>  {
    if(item.key==0){
      setFormValues(item);
      handleSelectStateModalVisible(true);
    }else if(item.key>0&&item.key<6){
      setFormValues(item);
      handleSelectAttrModalVisible(true);
    }else{
     addDesignAttrList(item);
    }
  }

  const addDesignAttrList = async (item) =>  {
   
    console.log("-------------------addDesignAttrList")
     console.log(updateIndex)
     console.log(item)
    let newList=[...designAttrList] ; 

    if(updateIndex!=null){
      newList[updateIndex]=item;
      setUpdateIndex(null);
    }else{
      item.i=new Date().getTime();
      newList.push(item)
    }
   
    setDesignAttrlist(newList);
    handleSelectAttrModalVisible(false);
    setFormValues({});
 }

 const saveTemplate = async () =>  {

  console.log(attrLayout)



   let template={
    stateList:designStateList,
    attrList:designAttrList,
    tabitem:items,
    attrLayout,
    stateLayout
   
   }
   console.log(template)
  //  localStorage.setItem("template",JSON.stringify(template))
  console.log(JSON.stringify(template).length)
  await updateDeviceType({"typeId":deviceType.typeId,"newTypeId":deviceType.typeId,"template":JSON.stringify(template)})

 }


 const addDesignStateList = async (item) =>  {

  let newList=[...designStateList] ; 

  if(updateIndex!=null){
    newList[updateIndex]=item;
    setUpdateIndex(null);
  }else{
    item.i=new Date().getTime();
    newList.push(item)
  }

  console.log( newList)
  setDesignStatelist(newList);
  handleSelectStateModalVisible(false);
  setFormValues({});
}


const delDesignStateList = async (index) =>  {
  let newList=[...designStateList] ; 
  newList.splice(index,1)
  setDesignStatelist(newList);
}

const delDesignAttrList = async (index) =>  {
  let newList=[...designAttrList] ; 
  newList.splice(index,1)
  setDesignAttrlist(newList);
}

  const option2 = {
    // color: ["red", "green", "yellow"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30,
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [0,1,2,3,4,5,6],
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed',
        },
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd', //左边线的颜色
        },
      },
    },
    yAxis: {
      type: 'value',
      // min:0,  //取0为最小刻度
      // max: 60, //取100为最大刻度
      axisLabel: {
        formatter: '{value}',
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd', //左边线的颜色
        },
      },
    },
    series:  [0,1,2,3],
  };

 



    const onChange = (index) => {
   
      console.log(index)
      setActiveKey(index);
    };

    const onEdit = (targetKey: string, action: 'add' | 'remove') => {
      if (action === 'add') {
        handTabModalVisible(true);
      } else {
        remove(targetKey);
      }
    };
  
    const remove = (targetKey) => {
      const newPanes = [...items];
      newPanes.splice(targetKey,1);
      setItems(newPanes)

      let newActiveKey = activeKey;

      if(targetKey<newActiveKey){
        newActiveKey--;
      }else if(targetKey==newActiveKey){
          newActiveKey=0
       
      }

     
      setItems(newPanes);
      setActiveKey(newActiveKey);
    };

    const edittabs = (index:number) => {
      if(items[index].label=='报警记录'){
        return;
      }
      setFormValues(items[index])
      handUpdateTabModalVisible(true);
  };

  const addTab = (item) => {
      const newActiveKey = items.length-1;
      const newPanes = [...items];
      item=formatchart(item);
      newPanes.splice(items.length-1,0, item)
      setActiveKey(newActiveKey);
      setItems(newPanes);
  };

  const updateTab = (item) => {
      const newPanes = [...items];
      item=formatchart(item);
      newPanes[activeKey]=item;
      setItems(newPanes);
      setActiveLabel(null);
  };


  const formatchart = (item) => {
    let chartoption={...option2};
    chartoption.legend.data=item.browseNames;
    chartoption.color=item.colors.replaceAll("，",",").split(",");
    let  series=[];
    for(let i=0;i<item.browseNames.length;i++){
      series.push({ 
        name: item.browseNames[i],
        type: item.chartType||'line',
        data: [0, 132, 101, 134, 90, 230, 210]
      })
    }
    if( item.chartType=='bar'){
      chartoption.xAxis.boundaryGap=true;
    }
    chartoption.series=series;
    item.chartData=chartoption;
    return item;

};

const updateAttr= (item,index) => {
  setUpdateIndex(index);

  setFormValues(item);

  handleSelectAttrModalVisible(true);
};




    const designItem = (item,index) => {
   
      var url = null;
      let key=item.i+"";
     
      switch (item.key) {
        case 1:
          url = (
            <div  key={key} className={styles.dataItem}  data-grid={attrLayout[index]||{x: index*3, y: 0, w: 3, h: 3, minW: 2, maxW: 4,i:key }}>
            <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
            <div onClick={()=>updateAttr(item,index)}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> 
                  <span className={styles.topRight} ></span>
              </div>
              <div className={styles.middleValue}><span   className={styles.data} >--</span><span className={styles.unit}>{item.unit}</span></div>
              <div className={styles.bottom}>
                <div className={styles.attribute}>{item.text}</div>
              </div>
            </div>
           </div>
          );
          break;
        case 2:
          url = (
            <div    key={key}  className={styles.dataItem}   data-grid={attrLayout[index]||{ x: index*3, y: 0, w: 3, h: 6, minW: 2, maxW: 4,i:key  }}>
              <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
              <div onClick={()=>updateAttr(item,index)}>
                <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>
                <div> 
                {item.fileds.map((filed ,filedindex) => (
                  <div style={{margin: '10px 0 10px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}> 
                  <span style={{color:'rgb(64 255 255)'}}>
                    <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
                    <span>{item.fileds[0]?.abb?.substring(1)}</span>
                  </span>
                  <div className={styles.dataBox} ><span className={styles.data1} >--</span>{item.unit}</div></div>
                  ))}
                
                </div>
                <div className={styles.bottom}>
                  <div className={styles.attribute}>{item.text}</div>
                </div >
                </div > 
            </div>
          );
          break;
        case 3:
            url = (  
            <div  key={key} className={styles.dataItem}   data-grid={attrLayout[index]||{ x: index*3, y: 0, w: 3, h: 3, minW: 2, maxW: 4 ,i:key }}>
              <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
              <div onClick={()=>updateAttr(item,index)}>
                <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>

                <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}>
                <span style={{color:'rgb(64 255 255)'}}>
                    <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
                    <span>{item.fileds[0]?.abb?.substring(1)}</span>
                  </span>
                  
                  <div className={styles.dataBox} ><span className={styles.data1} >--</span>{item.unit}</div></div>
                <div className={styles.bottom}>
                <div className={styles.attribute}>{item.text}</div>
              </div >
              </div > 
          </div>);
            break;
       case 4:
              url = (
                <div key={key}   className={styles.dataItem}  data-grid={attrLayout[index]||{ x: 1, y: 0*3, w: 3, h: 5, minW: 2, maxW: 4 ,i:key }}>
                  <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
                  <div onClick={()=>updateAttr(item,index)}>
                <div className={styles.flexBetween}>
                  <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
                  <span className={styles.topRight}></span>
                </div>
                <div>
                <div   className={styles.flex} >
                  <span style={{color:'rgb(64 255 255)'}}>
                    <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
                    <span>{item.fileds[0]?.abb?.substring(1)}</span>
                  </span>
                  <div className={styles.dataBox}>
                    <span className={styles.data1}>--</span>{item.unit}
                  </div>
                </div>
                <div className={styles.flexcenter}>
                {item.fileds.map((filed ,filedindex) => (
                 filedindex>0?
                  <div className={styles.flexColumn}>
                    <span className={styles.data2}>--</span>
                    <span className={styles.attr} >{filed?.abb}</span>
                  </div>
                  :null
                ))}
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.attribute}>{item.text}</div>
              </div >
              </div > 
            </div>
      );
              break;
            
              case 5:
                url = (
                  <div   key={key}  className={styles.dataItem}  data-grid={attrLayout[index]||{ x: index*3, y: 0, w: 3, h: 4, minW: 2, maxW: 4,i:key  }}>
                   <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
                   <div onClick={()=>updateAttr(item,index)}>
                  <div className={styles.flexBetween}>
                    <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
                    <span className={styles.topRight}></span>
                  </div>
                  <div>
                    <div className={styles.flexcenter1}>
                    {item.fileds.map((filed ,filedindex) => (
                   
                      <div className={styles.flexColumn}>
                        <span className={styles.data2}>--</span>
                        <span className={styles.attr} >{filed?.abb}</span>
                      </div>
                     
                    
                    ))}
                    </div>
                  </div>
                  <div className={styles.bottom}>
                <div className={styles.attribute}>{item.text}</div>
              </div > 
              </div > 
                </div>
        );
                break;
               
                 
        default:
          url = (
            <div  key={key} data-grid={attrLayout[index]||{ x: 12, y:0, w: 3, h: 12 ,i:key}} >
              <Card className={ styles.alarmBox}  >
              <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignAttrList(index)}/>
              <div className={styles.title1}>{item.text}</div>
              <div className={styles.alrmcontent} >
                { alarmlist.map((item,index) => {
                  if(alarmlist.length>12){
                    if(index%2==0){
                      return( <div className={styles.flexBetween} >
                        <div style={{flex:1}} className={styles.flex}>
                          <div className={styles.yuan}  ></div>
                          <span className={styles.baojingText}>{item.alarmDes}</span>
                        </div>
                        {alarmlist.length%2==0||alarmlist.length-1>index? <div className={styles.flex} style={{flex:1}}>
                          <div className={styles.yuan}   ></div>
                          <span className={styles.baojingText}>{alarmlist[index+1].alarmDes}</span>
                        </div>:<div className={styles.flex} style={{flex:1}}></div>}
                      </div>)
                    }
                  }else{
                    return  <div className={styles.flex} ><div className={styles.yuan}  ></div><span className={styles.baojingText}>{item.alarmDes}</span></div>
                  }
                 
                } )}
            </div>
            </Card>
            </div> 
          );
          break;
      }
      return url;
    }


    console.log(stateLayout)
    return (
      <div className={styles.main} key={1}>
        <div className={styles.flexEnd}>
          <Button className={styles.addBtn}   onClick={ saveTemplate}>
          保存模板
          </Button>
        </div>
        <Row gutter={16} className={styles.designContent}>
          <Col className="gutter-row" span={4}>
            <div className={styles.modellist}> <List
              size="large"
              bordered
              dataSource={modal}
              renderItem={item => <List.Item style={{display:'flex'}}><div style={{color:'white'}}  onClick={()=>toAddDesign(item)} >{item.text}    </div> {item.img?<Image src={item.img}  width={80} height={40}/>:null}</List.Item>}
            /></div>
         </Col>
      <Col className="gutter-row" span={20}>
        <div className={styles.content}>
        <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
           <Image    src={'/img/'  + deviceType.typeImg}  preview={false} width={54} height={54}/> 
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > -- </span>
                  <span className={styles.updateTimeText} > (最新同步时间：--)</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：-- </span>  
                    <span>&nbsp;  安装位置：--</span>
                  </div>
                  <div>最新维保日期:--</div>
                </div>  
            </div>
          </div>
        
        </div>
      </div>
      <div  style={{flex:3}} className={styles.dashboardContent}>
        <ResponsiveGridLayout    style={{    width:'100%'}}    rowHeight={45}  breakpoints={{lg: 1400, md: 996, sm: 768}} cols={{lg: 16, md: 16, sm: 16}}  onLayoutChange={(a)=>changelayout1(a)} >
          {designStateList.map((item,index) => (
              <div  key={item.i}  data-grid={stateLayout[index]||{ x: index*2, y: 0, w: 2, h: 1, minW: 2, maxW: 4 ,i:item.i }}>
                <div className={styles.state}  
                 >
                  <CloseOutlined  className={styles.closeIcon} onClick={()=>delDesignStateList(index)}/>
                  <div onClick={()=>{
                      setUpdateIndex(index);
                      setFormValues(item);
                      handleSelectStateModalVisible(true);
                    } }>
                    <div  className={ [styles.yuan, item.color=='green'? styles.bgGreen: item.color=='red'? styles.bgRed:styles.bgYellow].join(' ')}></div>
                    <span>{item.text}</span>
                  </div>
                </div>
              </div>
            ))}
          </ResponsiveGridLayout>
      </div>
     </div> 
          <ResponsiveGridLayout    style={{    width:'100%'}}    rowHeight={28}  breakpoints={{lg: 1400, md: 996, sm: 768}} cols={{lg: 15, md: 15, sm: 15}} margin={[10,10]}   onLayoutChange={(a)=>changelayout(a)} >
          {designAttrList.map((item,index) => (
            designItem(item,index)

          ))}</ResponsiveGridLayout>

        </div>
      </Col>
      </Row>
    <div>
      <Tabs
        onChange={onChange}
        type="editable-card"
        activeKey={activeKey+""}
        onEdit={onEdit}
        onTabClick={(e)=>edittabs(e)} 
      >
        {items.map((item,index) => (
          <Tabs.TabPane tab={item.label} key={index+""}     closable={item.closable} >
          {item.label!="报警记录"?<ECharts  style={{display:activeKey==index?'block':'none'}}   option={item.chartData} />:   <AlarmTable display={activeKey==index?'block':'none'} style={{display:activeKey==index?'block':'none'}}></AlarmTable>}
        </Tabs.TabPane>
        ))}
      </Tabs>

      {attrlist?<AddTabs
        onSubmit={async (value) => {
          addTab( value);
          handTabModalVisible(false);
        }}
        onCancel={() => {
          // setActiveLabel(null)
          handTabModalVisible(false);

        }}
        attrlist={attrlist}
        tabvalue={activeLabel}
        modalVisible={tabModalVisible}


        />:null}

      {formValues.label?<UpdateTabs
        onSubmit={async (value) => {
          updateTab( value);
          setFormValues({});
          handUpdateTabModalVisible(false);
        }}
        onCancel={() => {
          setFormValues({});
          handUpdateTabModalVisible(false);

        }}
        values={formValues}
        attrlist={attrlist}
        tabvalue={activeLabel}
        modalVisible={updateTabModalVisible}
        />:null}

      </div>
     {formValues.key?<SelectAttr
       onSubmit={async (value) => {
        await addDesignAttrList(value);
    
      }}
      onCancel={() => {
        handleSelectAttrModalVisible(false);
        setFormValues({});
        setUpdateIndex(null);
      }}
      values={formValues}
      attrlist={attrlist}
      modalVisible={selectAttrModalVisible}
      ></SelectAttr>:null} 

    {formValues.text?
      <SelectState
        onSubmit={async (value) => {  await addDesignStateList(value);}}
        onCancel={() => { handleSelectStateModalVisible(false);  setFormValues({}); setUpdateIndex(null);}}
        attrlist={attrlist}
        values={updateIndex!=null? formValues:{color:'green'}}
        modalVisible={selectStateModalVisible}
        >
      </SelectState>:null} 
 
      </div>



    )

  }

  export default details;